<template>
	<view>

	</view>
</template>

<script lang="ts" setup>
	import { ref , computed} from "vue"
	import { onLoad } from "@dcloudio/uni-app"
	import { useStore } from "vuex"
	import StrUtil from "@/utils/StrUtils.js"
	import DbUtil from "../../utils/DbUtil.js"
	
	const store = useStore()

	//从外部跳转过来的
	let fromOptions = ref(null)
	
	const userInfo = ref({})
	const shareUserInfo = ref({})
	
	const sxf_theater = uniCloud.importObject("sxf-theater");
	
	//首先判断是不是从分享过来的 65392e3ca09a9bd1a4496b0f
	onLoad(async (option) => {
		console.log("welcome option:", option)
		fromOptions.value = option
		
		// 模拟分享人
		// fromOptions.value.shareUserId = "f38056106724ad5511dbc8af39188f7d";
		// fromOptions.value.shareOpenId = "omdAMj1ekLgYUwac86h1po5FQdmg";
		
		console.log('----fromOptions:', fromOptions.value);
		
		// 获取分享人信息
		if (fromOptions.value.shareUserId !== undefined &&
			fromOptions.value.shareUserId != null && 
			fromOptions.value.shareUserId.length > 0) {
			// 有分享人
			const shareRes = await DbUtil.getInstance("ndp-theater-user").queryOne({
				appId: getApp().globalData.dcloudAppId,
				_id: fromOptions.value.shareUserId
			});
			shareUserInfo.value = shareRes;
			console.log("shareUserInfo:", shareUserInfo.value);
			if (shareUserInfo.value !== undefined && shareUserInfo.value != null) {
				userInfo.value["inviteUserId"] = fromOptions.value.shareUserId; // 邀请人用户userId
				userInfo.value["inviteUserName"] = shareUserInfo.value.userName; // 邀请人用户名
			}
		}
		// 分享人相关参数
		if (!StrUtil.isEmpty(fromOptions.value.shareUserId)) {
			getApp().globalData.shareUserId = fromOptions.value.shareUserId;
		}
		if (!StrUtil.isEmpty(fromOptions.value.shareOpenId)) {
			getApp().globalData.shareOpenId = fromOptions.value.shareOpenId;
		}
		console.log("shareUserId：", fromOptions.value.shareUserId);
		console.log("shareOpenId：", fromOptions.value.shareOpenId);
		
		// 获取当前用户信息
		await getOpenId();
		
		// 用户信息处理完成后，进行页面分发
		jumpPage(fromOptions);
	})
	
	
	const getOpenId = async () => {
		let openId = uni.getStorageSync(getApp().globalData.appId)
		console.log("openId", openId)
		// openId = "omdAMj1ekLgYUwac86h1po5FQdmg"
		if (StrUtil.isEmpty(openId)) {
			openId = await wxLogin()
		}
		if (!StrUtil.isEmpty(openId)) {
			getApp().globalData.curOpenId = openId;
		}
		
		//获得用户信息
		await getUserInfo(openId)
	}
	
	
	const getUserInfo = async (openId:string)=>{
		console.log("getUserInfo openId: ", openId);
		// 获取用户信息
		userInfo.value = await DbUtil.getInstance("ndp-theater-user").queryOne({
			appId: getApp().globalData.dcloudAppId,
			openId: openId
		});
		console.log("userInfo.value", userInfo.value);
		if (userInfo.value === undefined) {
			//如果是新用户
			await wxLogin();
			const total = await DbUtil.getInstance("ndp-theater-user").count({
				appId: getApp().globalData.dcloudAppId,
				openId: openId
			});
			console.log("appId=====", getApp().globalData.dcloudAppId);
			console.log("total=====", total);
			if (total == 0) {
				await saveUserInfo();
			}
		}
		
		if (userInfo.value !== undefined) {
			getApp().globalData.curUserId = userInfo.value._id;
			getApp().globalData.curUserInfo = userInfo.value;
			store.commit("setUserInfo", userInfo.value);
		}
	}

	const saveUserInfo = () => {
		return new Promise<void>(async (resolve, reject) => {
			console.log("saveUserInfo userInfo:", userInfo.value);
			DbUtil.getInstance("ndp-theater-user").updateOrSave(userInfo.value).then((res) => {
				console.log('----saveUserInfo updateOrSave:', res)
				userInfo.value._id = res.result.id
				resolve()
			})
		})
	}
	
	const wxLogin = () => {
		return new Promise<void>((resolve, reject) => {
			uni.login({
				provider: "weixin",
				success: (res) => {
					uni.getUserInfo({
						provider: "weixin",
						success: async (res1) => {
							let params = {
								"code": res.code,
								"rawData": res1.rawData,
								"nickName": res1.userInfo.nickName,
								"avatarUrl": res1.userInfo.avatarUrl,
								"signature": res1.signature,
								"encryptedData": res1.encryptedData,
								"iv": res1.iv,
							}
							const co1 = uniCloud.importObject("col-sxf")
							let wxSession = await co1.wxjscode2session(params)
							console.log("wxSession----:", wxSession.data)
							if (wxSession.data.errcode !== undefined) {
								uni.showToast({
									title: "失败:" + wxSession.data.errcode
								})
							} else {
								userInfo.value = {
									"nickName": res1.userInfo.nickName,
									"userName": res1.userInfo.nickName,
									"gender": res1.userInfo.gender,
									"avatarUrl": res1.userInfo.avatarUrl,
									"openId": wxSession.data.openid,
									// "unionId": wxSession.data.unionid,  // 开放平台的同一用户的唯一标识
									appId: getApp().globalData.dcloudAppId,
								}
								if (shareUserInfo.value !== undefined && shareUserInfo.value != null) {
									userInfo.value["inviteUserId"] = fromOptions.value.shareUserId; // 邀请人用户userId
									userInfo.value["inviteUserName"] = shareUserInfo.value.userName; // 邀请人用户名
								}
								console.log("wxlogin userInfo:", userInfo.value);
								uni.setStorageSync(getApp().globalData.appId, wxSession.data.openid)
								resolve(wxSession.data.openid)
							}
						},
					})
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}
	
	const jumpPage = (options) => {
		console.log("jumpPage 页面分发");
		console.log("fromOptions.value:", fromOptions.value);
		console.log("options:", options);
		
		// 页面跳转
		if (fromOptions.value.page === "main_page") {
			// 跳转到首页
			if (fromOptions.value.tab === "MainPage") {
				// uni.switchTab({
				// 	url: "/pages/ticker/list"
				// });
				console.log("检查detailId:", fromOptions.value.detailId)
				if (!StrUtil.isEmpty(fromOptions.value.detailId)) {
					// 有详情id才跳转到详情
					uni.redirectTo({
						url:"/pages/ticker/detail?id=" + fromOptions.value.detailId
					})
					return;
				}
			}
		}
		
		// 其他情况，直接跳转到首页
		uni.switchTab({
			url: "/pages/ticker/list"
		});
	}
</script>

<style lang="scss" scoped>
	.cButton {
		width: 300px;
		margin-top: 400px;
	}
	
	.avatar-button {
		flex: 1;
		height: 100%;
		padding: 0;
		font-size: 14px;
		line-height: 32px;
		background-color: #fff;
		border: none;
	}
	
	.avatar-button::after {
		border: none;
	}
	
	.avatar {
		width: 32px;
		height: 32px;
		border-radius: 50%;
	}
</style>